<template>
  <div class="products-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">商品管理</h1>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="商品编号">
          <el-select v-model="searchForm.productNumber" placeholder="请选择" clearable>
            <el-option label="RQ-8903-9888" value="RQ-8903-9888" />
            <el-option label="RQ-8903-9889" value="RQ-8903-9889" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品名称">
          <el-select v-model="searchForm.productName" placeholder="请选择" clearable>
            <el-option label="无人机" value="无人机" />
            <el-option label="手机" value="手机" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品型号">
          <el-select v-model="searchForm.productModel" placeholder="请选择" clearable>
            <el-option label="RQ0089" value="RQ0089" />
            <el-option label="RQ0090" value="RQ0090" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-section">
      <div class="action-left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!hasSelection">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="productNumber" label="商品编号" width="120" />
        <el-table-column prop="productName" label="商品名称" width="120" />
        <el-table-column prop="productModel" label="商品型号" width="120" />
        <el-table-column prop="quantity" label="商品数量" width="100" />
        <el-table-column prop="unit" label="商品单位" width="100" />
        <el-table-column prop="unitPrice" label="商品单价" width="120">
          <template #default="{ row }">
            ¥{{ Number(row.unitPrice ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" label="商品总价" width="120">
          <template #default="{ row }">
            ¥{{ Number(row.totalPrice ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="productType" label="商品类型" width="100" />
        <el-table-column prop="material" label="商品材质" width="100" />
        <el-table-column prop="brand" label="品牌名称" width="100" />
        <el-table-column prop="color" label="商品颜色" width="100" />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleDetail(row)">
              详细信息
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品编号" prop="productNumber">
              <el-input v-model="form.productNumber" placeholder="请输入商品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品型号" prop="productModel">
              <el-input v-model="form.productModel" placeholder="请输入商品型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入商品单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品单价" prop="unitPrice">
              <el-input-number v-model="form.unitPrice" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品类型" prop="productType">
              <el-select v-model="form.productType" placeholder="请选择商品类型" style="width: 100%">
                <el-option label="科技类" value="科技类" />
                <el-option label="生活类" value="生活类" />
                <el-option label="办公类" value="办公类" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品材质" prop="material">
              <el-input v-model="form.material" placeholder="请输入商品材质" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌名称" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品颜色" prop="color">
              <el-input v-model="form.color" placeholder="请输入商品颜色" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Upload, Download } from '@element-plus/icons-vue'
import api from '@/services/api'

export default {
  name: 'Products',
  components: {
    Search, Refresh, Plus, Delete, Upload, Download
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增商品')
    const formRef = ref()
    const selectedRows = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      productNumber: '',
      productName: '',
      productModel: '',
      dateRange: []
    })
    
    // 表格数据
    const tableData = ref([
      {
        id: 1,
        productNumber: 'RQ-8903-9888',
        productName: '无人机',
        productModel: 'RQ0089',
        quantity: 1,
        unit: '个',
        unitPrice: 100000.00,
        totalPrice: 100000.00,
        productType: '科技类',
        material: '钛刚',
        brand: '理程',
        color: '银灰色'
      }
    ])
    
    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 1
    })
    
    // 表单数据
    const form = reactive({
      id: null,
      productNumber: '',
      productName: '',
      productModel: '',
      quantity: 1,
      unit: '个',
      unitPrice: 0,
      totalPrice: 0,
      productType: '',
      material: '',
      brand: '',
      color: ''
    })
    
    // 表单验证规则
    const rules = reactive({
      productNumber: [
        { required: true, message: '请输入商品编号', trigger: 'blur' }
      ],
      productName: [
        { required: true, message: '请输入商品名称', trigger: 'blur' }
      ],
      productModel: [
        { required: true, message: '请输入商品型号', trigger: 'blur' }
      ],
      quantity: [
        { required: true, message: '请输入商品数量', trigger: 'blur' }
      ],
      unitPrice: [
        { required: true, message: '请输入商品单价', trigger: 'blur' }
      ]
    })
    
    // 计算属性
    const hasSelection = computed(() => selectedRows.value.length > 0)
    
    // 获取商品列表
    const fetchProducts = async () => {
      loading.value = true
      try {
        const response = await api.get('/products', {
          params: {
            page: pagination.currentPage,
            size: pagination.pageSize,
            ...searchForm
          }
        })
        
        if (response.data.code === 200) {
          const rawList = response.data.data.list || []
          // 将后端字段映射为表格所需字段，并补齐缺省值
          tableData.value = rawList.map((item) => ({
            id: item.id,
            productNumber: item.productNumber ?? '',
            productName: item.productName ?? '',
            productModel: item.productModel ?? '',
            quantity: item.stock ?? 0,
            unit: item.unit ?? '',
            unitPrice: item.price ?? 0,
            totalPrice: (item.price ?? 0) * (item.stock ?? 0),
            productType: item.category ?? '',
            material: item.material ?? '-',
            brand: item.brand ?? '-',
            color: item.color ?? '-',
            status: item.status ?? true,
            created_at: item.created_at ?? ''
          }))
          pagination.total = response.data.data.total || 0
        }
      } catch (error) {
        ElMessage.error('获取商品列表失败')
        console.error('获取商品列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchProducts()
    }
    
    // 重置搜索
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = key === 'dateRange' ? [] : ''
      })
      handleSearch()
    }
    
    // 新增
    const handleAdd = () => {
      dialogTitle.value = '新增商品'
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑
    const handleEdit = (row) => {
      dialogTitle.value = '编辑商品'
      Object.assign(form, row)
      dialogVisible.value = true
    }
    
    // 查看详情
    const handleDetail = (row) => {
      ElMessage.info(`查看商品详情: ${row.productName}`)
    }
    
    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await api.delete(`/products/${row.id}`)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          fetchProducts()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 批量删除
    const handleBatchDelete = async () => {
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个商品吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const ids = selectedRows.value.map(row => row.id)
        const response = await api.delete('/products/batch', { data: { ids } })
        if (response.data.code === 200) {
          ElMessage.success('批量删除成功')
          fetchProducts()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }
    
    // 导入
    const handleImport = () => {
      ElMessage.info('导入功能开发中...')
    }
    
    // 导出
    const handleExport = () => {
      ElMessage.info('导出功能开发中...')
    }
    
    // 表格选择变化
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      fetchProducts()
    }
    
    // 当前页变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      fetchProducts()
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
      } catch (error) {
        return
      }
      
      submitLoading.value = true
      
      const isEdit = !!form.id
      
      try {
        const url = isEdit ? `/products/${form.id}` : '/products'
        const method = isEdit ? 'put' : 'post'
        
        const response = await api[method](url, form)
        if (response.data.code === 200) {
          ElMessage.success(isEdit ? '更新成功' : '创建成功')
          dialogVisible.value = false
          fetchProducts()
        }
      } catch (error) {
        const errorMessage = error.response?.data?.message || (isEdit ? '更新失败' : '创建失败')
        ElMessage.error(errorMessage)
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        id: null,
        productNumber: '',
        productName: '',
        productModel: '',
        quantity: 1,
        unit: '个',
        unitPrice: 0,
        totalPrice: 0,
        productType: '',
        material: '',
        brand: '',
        color: ''
      })
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      resetForm()
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    onMounted(() => {
      fetchProducts()
    })
    
    return {
      loading,
      submitLoading,
      dialogVisible,
      dialogTitle,
      formRef,
      searchForm,
      tableData,
      pagination,
      form,
      rules,
      hasSelection,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleDetail,
      handleDelete,
      handleBatchDelete,
      handleImport,
      handleExport,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleSubmit,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
.products-page {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: var(--background-base);
  border-radius: 8px;
}

.search-form {
  margin: 0;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left {
  display: flex;
  gap: 10px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .action-section {
    flex-direction: column;
    gap: 10px;
  }
  
  .action-left {
    flex-wrap: wrap;
  }
}
</style>
